package com.anjiplus.template.gaea.business.config;

import com.anjiplus.template.gaea.business.util.DesUtil;
import com.anjiplus.template.gaea.business.util.MacUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class LicenseCheckInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LicenseCheckInterceptor.class);


    private static String readLicense() throws Exception{
        String s = "";
        StringBuffer content = new StringBuffer();
        InputStreamReader in = new InputStreamReader(new FileInputStream(new File("LICENSE_LOCAL")), "UTF-8");
        BufferedReader br = new BufferedReader(in);
        while ((s = br.readLine()) != null) {
            content = content.append(s);
        }
        return content.toString();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        try {
            String licenseOrigin = readLicense();
            String license = DesUtil.getDecryptString(licenseOrigin);

            JSONObject jsonObject = new JSONObject(license);
            JSONArray licenseMac = jsonObject.getJSONArray("mac");
            String licenseUntilDate = jsonObject.getString("untilDate");

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date untilDate = sdf.parse(licenseUntilDate);
            Date now = new Date();
            String mac = MacUtil.getMACAddress();

            //判断获取的服务器mac地址  与  license中的mac地址，是否相同
            if (!licenseMac.toString().equals("[]") &&!licenseMac.toString().contains(mac)) {
                log.error("MAC地址未授权：{}", mac);
                response.sendRedirect("/noLicense/1");
                return false;
            } else if (now.after(untilDate)) {
                log.error("license过期：{}", licenseUntilDate);
                response.sendRedirect("/noLicense/2");
                return false;
            } else {
                return true;
            }
        }catch (Exception e){
            try {
                response.sendRedirect("/noLicense/2");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        }

        //去掉license检测，直接返回true
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
